﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class Solution160
{
    public ListNode GetIntersectionNode2(ListNode headA, ListNode headB)
    {

        ListNode a = headA;
        ListNode b = headB;

        while (a != null && b != null)
        {
            a=a.next; b=b.next;


        }//结束时有一个先到达终点

        ListNode b2 = headB;//b先出发
        ListNode a2 = headA;
        if (a != null) {



            while (a != null) {

                a = a.next;
                a2 = a2.next;
            }


            


        }
        else
        {
            while (b != null)
            {

                b= b.next;
                b2 = b2.next;
               
            }
        }

        while (a2 != b2) {

            b2 = b2.next;

            a2 = a2.next;
        }//


        
        //a2也可能是null，没交点


            return a2;


    }
    //更优雅，不需要新创建指针
    public ListNode GetIntersectionNode(ListNode headA, ListNode headB)
    {

        ListNode a = headA;
        ListNode b = headB;

        while (a != b)
        {
            if (a == null) {
                a = headB;
            }
            else
            {
                a= a.next;
            }

            if (b == null)
            {
                b = headA;
            }
            else
            {
                b = b.next;
            }


            


        }//结束时有一个先到达终点

 

        return a;


    }
}
